package com.notary.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.notary.config.JuHeConfig;
import com.notary.entity.vo.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JuHeUtil {

    @Autowired
    private JuHeConfig juHeConfig;

    public JsonResult sendSms(String mobileNo, String templateID, Map<String, String> paramMap) {
        String strUrl = juHeConfig.getSmsInfo().getUrl();
        String appKey = juHeConfig.getSmsInfo().getAppKey();
        if("fzid".equals(templateID)) templateID = juHeConfig.getSmsInfo().getFzid();
        String method = "POST";
        String result = null;
        log.info("聚合数据短信发送，入参：mobileNo：{}，templateID：{}，paramMap：{}", mobileNo, templateID, JSON.toJSONString(paramMap));
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            sb.append("#").append(entry.getKey()).append("#").append("=").append(entry.getValue()).append("&");
        }
        Map params = new HashMap();
        params.put("mobile", mobileNo);
        params.put("tpl_id", templateID);
        params.put("tpl_value", sb.toString());
        params.put("key", appKey);
        try {
            result = HttpUtil.net(strUrl, params, method);
        } catch (Exception e) {
            log.error("调聚合数据短信接口短信发送异常！", e.getMessage());
            return JsonResult.fail("调聚合数据短信接口短信发送异常！");
        }
        JSONObject object = JSONObject.parseObject(result);
        if (object == null) {
            log.error("调聚合数据短信接口短信发送返回为空！");
            return JsonResult.fail("调聚合数据短信接口短信发送失败，返回为空");
        } else if (!"0".equals(object.getString("error_code"))) {
            log.error("调聚合数据短信接口短信发送失败！", object);
            return JsonResult.fail("调聚合数据短信接口短信发送失败：" + object.getString("reason"));
        }
        log.info("调用聚合数据短信接口短信发送成功！", object);
        return JsonResult.success("调用聚合数据短信接口短信发送成功");
    }

}
